<?php
/**
 * Created by PhpStorm.
 * userValidate: hms
 * Date: 2018/8/7
 * Time: 9:40
 */
use app\index\model\Config;
use sms\Rest;
include_once("../../extend/sms/Rest.php");


function createOrderNo($prefix = 'L')
{
    return $prefix . (strtotime(date('YmdHis', time()))) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
}

//手机掩码
function maskMobile($mobile) {
    $prefix = substr($mobile, 0, 3);
    $suffix = substr($mobile, -4, 4);
    $maskMobile = $prefix . " **** " . $suffix;
    return $maskMobile;
}

//银行卡掩码
function maskBankNum($bank) {
    $prefix = substr($bank, 0, 4);
    $suffix = substr($bank, -4, 4);
    $maskBankCardNo = $prefix." **** **** **** ".$suffix;
    return $maskBankCardNo;
}

//姓名掩码
function starReplace($name, $num = 0)
{
    if ($num && mb_strlen($name, 'UTF-8') > $num) {
        return mb_substr($name, 0, 4) . '*';
    }
    if ($num && mb_strlen($name, 'UTF-8') <= $num) {
        return $name;
    }

    $doubleSurname = [
        '欧阳', '太史', '端木', '上官', '司马', '东方', '独孤', '南宫',
        '万俟', '闻人', '夏侯', '诸葛', '尉迟', '公羊', '赫连', '澹台', '皇甫', '宗政', '濮阳',
        '公冶', '太叔', '申屠', '公孙', '慕容', '仲孙', '钟离', '长孙', '宇文', '司徒', '鲜于',
        '司空', '闾丘', '子车', '亓官', '司寇', '巫马', '公西', '颛孙', '壤驷', '公良', '漆雕', '乐正',
        '宰父', '谷梁', '拓跋', '夹谷', '轩辕', '令狐', '段干', '百里', '呼延', '东郭', '南门', '羊舌',
        '微生', '公户', '公玉', '公仪', '梁丘', '公仲', '公上', '公门', '公山', '公坚', '左丘', '公伯',
        '西门', '公祖', '第五', '公乘', '贯丘', '公皙', '南荣', '东里', '东宫', '仲长', '子书', '子桑',
        '即墨', '达奚', '褚师', '吴铭'
    ];

    $surname = mb_substr($name, 0, 2);
    if (in_array($surname, $doubleSurname)) {
        $name = mb_substr($name, 0, 2) . str_repeat('*', (mb_strlen($name, 'UTF-8') - 2));
    } else {
        $number = mb_strlen($name, 'UTF-8');
        if($number < 2){
            return $name;
        }elseif($number == 2){
            $name = mb_substr($name, 0, 1) . str_repeat('*', (mb_strlen($name, 'UTF-8') - 1));
        }else{
            $name = mb_substr($name, 0, 1) . '*' .mb_substr($name, $number-1, $number);
        }
    }
    return $name;
}

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

function createRandomNum($length = 10) {
    $characters = '023456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

/**
 * 二位数组去重
 * @param $array
 * @param $fix
 * @return array
 */
function remove_duplicate($array , $fix){
    $result=array();
    foreach ($array as $key => $value) {
        $has = false;
        foreach($result as $val){
            if($val[$fix]==$value[$fix]){
                $has = true;
                break;
            }
        }
    if(!$has)
        $result[]=$value;
    }
    return $result;
}

//生成验证码
function redisCode($tel,$type){
    $redis = \redis\Redis::instance();
    $num = rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
    $code = $redis->set($type . $tel,$num);
    $time = $redis->expire($type . $tel,300);
    if($code && $time){
        return $num;
    }  else {
        return false;
    }
}

//图片bases64转换
function base64_image_content($base64_image_content,$path){
    //匹配出图片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        $type = $result[2];
        $new_file = $path."/".date('Ymd',time())."/";
        if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700);
        }
        $new_file = $new_file.time().".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            return $new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/*
 * sms调用公共方法
 * $templateId 模板id
 * $type 短信类型
 * $tel 电话
 * $code 验证码
 * $val 普通信息模板信息
 */
function sms($templateId,$type,$tel,$code='',$val='') {
    require_once  './vendor/autoload.php';
    date_default_timezone_set('PRC');
    $sms = new \PFinal\Aliyun\AliyunSMS();
    
    $sms->accessKeyId = 'LTAIGtC0LFn8Iwjg';
    $sms->accessKeySecret = 'mvsZxrZ5qyL2oAOKEbWQ86Fk8nwpHP';
    $sms->signName = '中维';
    $sms->templateId = $templateId;
    //$sms->templateCodeKey = '{}';
    
    if($type == 'code'){
        //发验证码
        $res = $sms->sendCode($tel, $code);
    }else{
        //发普通模板短信
        $res = $sms->templateSMS($tel,$templateId, $val);
    }
    return $res;
}

/**
 * accessToken
 * @return string
 */
function accessToken(){
    //c6d889d1-9810-4cc3-8ecc-8b2c3a40e4ab
    $accessToken = md5($_SERVER['REQUEST_TIME_FLOAT'] . uniqid('',true));
    $startNum    = 8;
    for($i = 0 ;$i < 4; ++$i){
        $accessToken = substr_replace($accessToken,'_',$startNum,0);
        $startNum   += 5;
    }
    return $accessToken;
}

/**
 * 获取一周的开始和结束时间
 * @param $date
 * @return array
 */
function getWeek($date)
{
    $first=1;
    $w=date('w',strtotime($date));
    $now_start=date('Y-m-d',strtotime("$date -".($w ? $w - $first : 6).' days'));
    $now_end=date('Y-m-d',strtotime("$now_start +6 days"));
    $arr = [
        'start' => $now_start . ' 00:00:00',
        'end' => $now_end . ' 23:59:59'
    ];
    return $arr;
}

/**
 * 发送模板短信
 * @param to 手机号码集合,用英文逗号分开
 * @param datas 内容数据 格式为数组 例如：array('Marry','Alon')，如不需替换请填 null
 * @param $tempId 模板Id
 */
function sendTemplateSMS($to,$datas,$tempId=593790)
{
    $accountSid= '8aaf070871bf69700172022c7bc31bbf';//主帐号
    $accountToken= 'e1362a8fc8454202b61949f721693373';//主帐号Token
    $appId='8aaf070871bf69700172022c7c151bc5';//应用Id
    $rest = new Rest('app.cloopen.com','8883','2013-12-26');
    $rest->setAccount($accountSid,$accountToken);
    $rest->setAppId($appId);

    // 发送模板短信
    $result = $rest->sendTemplateSMS($to,$datas,$tempId);
    if($result == NULL ) {
        echo "result error!";
        return false;
    }
    if($result->statusCode!=0) {
        echo "error code :" . $result->statusCode . "<br>";
        echo "error msg :" . $result->statusMsg . "<br>";
        return false;
        //TODO 添加错误处理逻辑
    }else{
        // 获取返回信息
        $smsmessage = $result->TemplateSMS;
        echo "dateCreated:".$smsmessage->dateCreated."<br/>";
        echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
        return true;
        //TODO 添加成功处理逻辑
    }
}



/*
	发送短信 - 云片网
*/
function SmsToSend($mobile,$code){
    $username='454922379';
    $password='6DDD9161A1FAD476E4310CC347A80C24';
    $gwid='6afc67b5';
    $message = "【好融艺】您的验证码为".$code;
    $curl="http://jk.smstcby.com/smsUTF8.aspx?type=send&username=".$username."&password=".$password."&gwid=".$gwid."&mobile=".$mobile."&message=".$message."&rece=json";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $curl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //https请求 不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //https请求 不验证HOST
    $json_data = curl_exec($ch);
    curl_close($ch);
	$array = json_decode($json_data, true);
    if($array['code']!=0){
        $array['msg'] = $array['remark'];
    }
	return $array;







//	$apikey = confvs('secretKey','sms'); //修改为您的apikey(https://www.yunpian.com)登录官网后获取
//	$url = confvs('sms_url','sms');
//	$tpl_id = confvs('sms_free_sign_name','sms').'您的验证码是'.$code;
//
//	$ch = curl_init();
//
//	/* 设置验证方式 */
//	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));
//
//	/* 设置返回结果为流 */
//	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//
//	/* 设置超时时间*/
//	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//
//	/* 设置通信方式 */
//	curl_setopt($ch, CURLOPT_POST, 1);
//	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//
//	// 发送短信
//	$data = array('text' => $tpl_id, 'apikey' => $apikey, 'mobile' => $mobile);
//
//	curl_setopt($ch, CURLOPT_URL, $url);
//	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
//	$json_data = curl_exec($ch);
//
//	$array = json_decode($json_data, true);
//
//	curl_close($ch);
//
//	return $array;
}

/**
 * @Title: confv
 * @Description: todo(获取配置值)
 * @param string $k
 * @param string $type
 * @return string
 * @throws
 */
function confvs($k, $type = 'web'){
    $config = new Config();
    return $config->confv($k, $type);
}

/*
 * 文件上传
 * @param $file 上传的文件
 * @param $fileName 存储的文件名
 * @return string
 * @throws
 */
function upload($file, $fileName) {
    // 移动到框架应用根目录/public/uploads/ 目录下
    if ($file) {
        $info = $file->validate(['size' => 320000000, 'ext' => 'rar,zip,doc,docx,pdf,jpg,png,jpeg'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $fileName);
        if ($info) {
            // 成功上传后 获取上传信息
            // 输出 jpg
            // echo $info->getExtension();
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            return $info->getSaveName();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
            // echo $info->getFilename();
        } else {
            // 上传失败获取错误信息
            return $file->getError();
        }
    }
}



/**
 * 企业端资料上传
 * @param $file 上传的文件
 * @param $fileName 存储的文件名
 * @param $dir 文件存储路径
 * @return string
 * @throws
 */
function companyUpload($file,$dir) {
    // 移动到框架应用根目录/public/uploads/ 目录下
    if ($file) {
        $info = $file->validate(['size' => 320000000, 'ext' => 'rar,zip,doc,docx,pdf,jpg,png,jpeg'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $dir);
        if ($info) {
            return array('status'=>1,'fileName'=>$info->getSaveName());
        } else {
            // 上传失败获取错误信息
            return  array('status'=>0,'msg'=>$file->getError());
        }
    }


    function getHttpHost ()
    {
        $protocol = (
            !empty($_SERVER['HTTPS']) &&
            $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

        return $protocol.$_SERVER['HTTP_HOST'];
    }
}

function ToGetEXECL($tableheader,$data,$filename){
    //引入类
    vendor('Classes.PHPExcel');
    $excel = new PHPExcel();
    $letter = array('A','B','C','D','E','F','G','H','I','J','K');
    for($i = 0;$i < count($tableheader);$i++) {
        $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
    }
    for ($i = 2;$i <= count($data) + 1;$i++) {
        $j = 0;
        foreach ($data[$i - 2] as $key=>$value) {
            $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
            $j++;
        }
    }
    $write = new PHPExcel_Writer_Excel5($excel);
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");;
    header('Content-Disposition:attachment;filename="'.$filename.'.xls"');
    header("Content-Transfer-Encoding:binary");
    $write->save('php://output');
}



//同步拼车车
function pccTb($mobile)
{
    $url = 'https://api.shengshihaotong.com/app/ums/other/auth/open';
    $token='eT5aA5iE2aB5lC6hO9eL5zI6rZ1bG6jY';
    $data = [
        'userAccount' =>trim($mobile),
    ];
    $headers = array(
        'Content-Type: application/json',
        "token:$token"
    );
    $post_data=json_encode($data);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);//不抓取头部信息。只返回数据
    curl_setopt($curl, CURLOPT_TIMEOUT, 60);//超时设置
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//1表示不返回bool值
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //https请求 不验证证书
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); //https请求 不验证HOST
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//重点
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    $data = curl_exec($curl);
//    if (curl_errno($curl)) {
//        return curl_error($curl);
//    }
    curl_close($curl);
    return json_decode($data);
}




